package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.PayAccount;
import org.dromara.system.mapper.EmailAccountMapper;
import org.dromara.system.mapper.PayAccountMapper;
import org.dromara.system.service.IEmailAccountService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.EmailConfigBo;
import org.dromara.system.domain.vo.EmailConfigVo;
import org.dromara.system.domain.EmailConfig;
import org.dromara.system.mapper.EmailConfigMapper;
import org.dromara.system.service.IEmailConfigService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 支付邮件配置Service业务层处理
 *
 * @author Gavino
 * @date 2025-01-13
 */
@RequiredArgsConstructor
@Service
public class EmailConfigServiceImpl implements IEmailConfigService {

    private final EmailConfigMapper baseMapper;
    private final IEmailAccountService emailAccountService;
    private final PayAccountMapper payAccountMapper;

    /**
     * 查询支付邮件配置
     *
     * @param configId 主键
     * @return 支付邮件配置
     */
    @Override
    public EmailConfigVo queryById(Long configId) {
        EmailConfigVo vo = baseMapper.selectVoById(configId);
        if (vo.getEmailAccountId().startsWith(",")) {
            vo.setEmailAccountId(vo.getEmailAccountId().substring(1));
        }
        if (vo.getEmailAccountId().endsWith(",")) {
            vo.setEmailAccountId(vo.getEmailAccountId().substring(0, vo.getEmailAccountId().length() - 1));
        }
        if (vo.getPayAccountId().startsWith(",")) {
            vo.setPayAccountId(vo.getPayAccountId().substring(1));
        }
        if (vo.getPayAccountId().endsWith(",")) {
            vo.setPayAccountId(vo.getPayAccountId().substring(0, vo.getPayAccountId().length() - 1));
        }
        return vo;
    }

    /**
     * 分页查询支付邮件配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 支付邮件配置分页列表
     */
    @Override
    public TableDataInfo<EmailConfigVo> queryPageList(EmailConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EmailConfig> lqw = buildQueryWrapper(bo);
        Page<EmailConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.setRecords(result.getRecords().stream().peek(obj -> {
            if (obj.getEmailAccountId().startsWith(",")) {
                obj.setEmailAccountId(obj.getEmailAccountId().substring(1));
            }
            if (obj.getEmailAccountId().endsWith(",")) {
                obj.setEmailAccountId(obj.getEmailAccountId().substring(0, obj.getEmailAccountId().length() - 1));
            }
            if (obj.getPayAccountId().startsWith(",")) {
                obj.setPayAccountId(obj.getPayAccountId().substring(1));
            }
            if (obj.getPayAccountId().endsWith(",")) {
                obj.setPayAccountId(obj.getPayAccountId().substring(0, obj.getPayAccountId().length() - 1));
            }
        }).toList());
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的支付邮件配置列表
     *
     * @param bo 查询条件
     * @return 支付邮件配置列表
     */
    @Override
    public List<EmailConfigVo> queryList(EmailConfigBo bo) {
        LambdaQueryWrapper<EmailConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EmailConfig> buildQueryWrapper(EmailConfigBo bo) {
        LambdaQueryWrapper<EmailConfig> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getConfigId() != null, EmailConfig::getConfigId, bo.getConfigId());
        lqw.eq(bo.getStatus() != null, EmailConfig::getStatus, bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getEmailAccountId()), EmailConfig::getEmailAccountId, "," + bo.getEmailAccountId() + ",");
        lqw.like(StringUtils.isNotBlank(bo.getPayAccountId()), EmailConfig::getPayAccountId, "," + bo.getPayAccountId() + ",");
        lqw.eq(bo.getTemplateId() != null, EmailConfig::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getCreateId() != null, EmailConfig::getCreateId, bo.getCreateId());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), EmailConfig::getRemark, bo.getRemark());
        if (!LoginHelper.isSuperAdmin()) {
            lqw.eq(EmailConfig::getCreateId, LoginHelper.getUserId());
        }
        return lqw;
    }

    /**
     * 新增支付邮件配置
     *
     * @param bo 支付邮件配置
     * @return 是否新增成功
     */
    @Transactional
    @Override
    public Boolean insertByBo(EmailConfigBo bo) {
        EmailConfig add = MapstructUtils.convert(bo, EmailConfig.class);
        add.setCreateId(LoginHelper.getUserId());
        add.setCreateName(LoginHelper.getUsername());
        add.setCreateTime(DateUtils.getNowDate());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            updateEmailAccountType(add.getCreateId());
        }
        return flag;
    }

    /**
     * 修改支付邮件配置
     *
     * @param bo 支付邮件配置
     * @return 是否修改成功
     */
    @Transactional
    @Override
    public Boolean updateByBo(EmailConfigBo bo) {
        if (!LoginHelper.isSuperAdmin()) {
            EmailConfig old = baseMapper.selectById(bo.getConfigId());
            if (!Objects.equals(old.getCreateId(), LoginHelper.getUserId())) {
                return false;
            }
        }
        EmailConfig update = MapstructUtils.convert(bo, EmailConfig.class);
        update.setUpdateId(LoginHelper.getUserId());
        update.setUpdateName(LoginHelper.getUsername());
        update.setUpdateTime(DateUtils.getNowDate());
        validEntityBeforeSave(update);
        boolean tag = baseMapper.updateById(update) > 0;
        if (tag) {
            updateEmailAccountType(update.getCreateId());
        }
        return tag;
    }

    /**
     * 修改邮箱账号类型
     *
     * @param agentId 代理ID
     */
    @Transactional
    public void updateEmailAccountType(Long agentId) {

        //查询代理的所有邮箱配置
        List<EmailConfig> configs = baseMapper.selectList(new LambdaQueryWrapper<EmailConfig>().eq(EmailConfig::getCreateId, agentId));

        //整理出所有配置的邮箱账号ID
        Set<Long> accountIds = new HashSet<>();
        for (EmailConfig config : configs) {
            if (StringUtils.isNotBlank(config.getEmailAccountId())) {
                String[] arr = config.getEmailAccountId().split(",");
                for (String str : arr) {
                    if (StringUtils.isNotBlank(str)) {
                        accountIds.add(Long.parseLong(str));
                    }
                }
            }
        }

        //更新邮箱账号类型
        emailAccountService.updateAgentAccountAType(agentId, null, 1, 0);
        if (!accountIds.isEmpty()) {
            emailAccountService.updateAgentAccountAType(agentId, new ArrayList<>(accountIds), null, 1);
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EmailConfig entity) {
        if (entity.getCreateId() == null) {
            throw new RuntimeException("代理ID不能为空");
        }
        if (StringUtils.isBlank(entity.getEmailAccountId())) {
            throw new RuntimeException("邮箱账号ID不能为空");
        }
        if (StringUtils.isBlank(entity.getPayAccountId())) {
            throw new RuntimeException("收款账号ID不能为空");
        }

        List<String> accounts = Arrays.stream(entity.getPayAccountId().split(",")).filter(StringUtils::isNotBlank).toList();

        //查询代理的所有邮箱配置
        LambdaQueryWrapper<EmailConfig> query = new LambdaQueryWrapper<EmailConfig>().eq(EmailConfig::getCreateId, entity.getCreateId());
        if(entity.getConfigId() != null) {
            query.ne(EmailConfig::getConfigId, entity.getConfigId());
        }
        List<EmailConfig> configs = baseMapper.selectList(query);

        configs.forEach(config -> Arrays.stream(config.getPayAccountId().split(",")).forEach(accountId -> {
            if (accounts.contains(accountId)) {
                PayAccount account = payAccountMapper.selectById(accountId);
                throw new RuntimeException("收款账号[" + account.getAccountName() + "]在其他配置中已存在，请勿重复配置");
            }
        }));

        if (!entity.getEmailAccountId().startsWith(",")) {
            entity.setEmailAccountId("," + entity.getEmailAccountId());
        }
        if (!entity.getEmailAccountId().endsWith(",")) {
            entity.setEmailAccountId(entity.getEmailAccountId() + ",");
        }
        if (!entity.getPayAccountId().startsWith(",")) {
            entity.setPayAccountId("," + entity.getPayAccountId());
        }
        if (!entity.getPayAccountId().endsWith(",")) {
            entity.setPayAccountId(entity.getPayAccountId() + ",");
        }
    }

    /**
     * 校验并批量删除支付邮件配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }

        if (!LoginHelper.isSuperAdmin()) {
            return baseMapper.delete(new LambdaQueryWrapper<EmailConfig>().in(EmailConfig::getConfigId, ids).eq(EmailConfig::getCreateId, LoginHelper.getUserId())) > 0;
        }

        return baseMapper.deleteByIds(ids) > 0;
    }
}
